import { IResPage } from '@/services';
import { ProFormInstance } from '@ant-design/pro-components';
import { useAntdTable, useSize } from 'ahooks';
import { AntdTableOptions, Params } from 'ahooks/lib/useAntdTable/types';
import { Pagination, Table, TableProps } from 'antd';
import { useRef } from 'react';
import styles from './index.less';

export const formatPageParams = ([{ pageSize, current }, params]: Params) => {
  return {
    ...params,
    page: current,
    size: pageSize,
  };
};

export function useTable<T, U extends Params>(
  service: (params: any) => Promise<IResPage<T>>,
  options?: AntdTableOptions<{ list: T[]; total: number }, U>,
) {
  const form = useRef<ProFormInstance>();
  const antdTable = useAntdTable(
    (...params: U) =>
      service(formatPageParams(params)).then((res) => ({
        total: res.data.pagedInfo.total,
        list: res.data.pageData,
      })),
    { ...options, form: form.current },
  );
  return {
    ...antdTable,
    form,
  };
}

export function ZLTable<T extends Object>({
  header,
  pagination,
  onChange,
  ...tableProps
}: {
  header?: React.ReactNode;
} & TableProps<T>) {
  const containerRef = useRef<HTMLDivElement>(null);
  const tableRef = useRef<HTMLDivElement>(null);
  const tableSize = useSize(tableRef.current);
  const containerSize = useSize(containerRef.current);

  const height = (containerSize?.height || 0) - 56;
  return (
    <>
      {header}
      <div ref={containerRef} className={styles.tableContainer}>
        <Table
          {...tableProps}
          ref={tableRef}
          size="small"
          bordered
          pagination={false}
          scroll={{
            y: height <= (tableSize?.height || Infinity) ? height : undefined,
            x: tableProps.scroll?.x,
          }}
        />
      </div>
      <div className={styles.footer}>
        {pagination && (
          <div className={styles.desc}>共 {pagination.total} 条</div>
        )}
        <Pagination
          {...pagination}
          className={styles.pagination}
          onChange={(page, pageSize) => {
            onChange?.({ pageSize: pageSize, current: page }, {}, [], {
              currentDataSource: tableProps.dataSource as any,
              action: 'paginate',
            });
          }}
        />
      </div>
    </>
  );
}
